var sy = sy || {};

layer.config({
    extend: 'extend/layer.ext.js'
});

sy.contextPath = "http://localhost:8080";
/**
 * 扩展tree和combotree，使其支持平滑数据格式
 * @requires jQuery,EasyUI
 * 
 */
sy.loadFilter = {
	loadFilter : function(data, parent) {
		var opt = $(this).data().tree.options;
		var idField, textField, parentField;
		if (opt.parentField) {
			idField = opt.idField || 'id';
			textField = opt.textField || 'text';
			parentField = opt.parentField || 'pid';
			var i, l, treeData = [], tmpMap = [];
			for (i = 0, l = data.length; i < l; i++) {
				tmpMap[data[i][idField]] = data[i];
			}
			for (i = 0, l = data.length; i < l; i++) {
				if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
					if (!tmpMap[data[i][parentField]]['children'])
						tmpMap[data[i][parentField]]['children'] = [];
					data[i]['text'] = data[i][textField];
					tmpMap[data[i][parentField]]['children'].push(data[i]);
				} else {
					data[i]['text'] = data[i][textField];
					treeData.push(data[i]);
				}
			}
			return treeData;
		}
		return data;
	}
};

sy.fnredraw = function(param,url,t){
	var oSettings = t.fnSettings();
	if(url.indexOf('?')==-1) url+="?";
	else url = url+"&";
	$.each(param,function(i,v){
		url+=i+"="+v+"&";
	});
	url.substring(0,url.length-1);
	oSettings.ajax = url;
	t.fnDraw();
}

sy.amap = function(callback,lat,lng) {
	var dialog = parent.sy.modalDialog({
		title : '地图',
		width:800,    
	    height:600,
		url : "/manager/admin/go/amap?lat="+lat+"&lng="+lng,
		buttons : [ {
			text : '确定',
			handler : function() {
				dialog.find('iframe').get(0).contentWindow.submitLocation(dialog, callback, parent.$);
			}
		} ]
	});
};

sy.bmap = function(callback,lat,lng) {
	var dialog = parent.sy.modalDialog({
		title : '地图',
		width:800,    
	    height:600,
		url : sy.contextPath + "/go.do?path=common/bmap&lat="+lat+"&lng="+lng,
		buttons : [ {
			text : '确定',
			handler : function() {
				dialog.find('iframe').get(0).contentWindow.submitLocation(dialog, callback, parent.$);
			}
		} ]
	});
};
 
sy.validateForm=function(selector){
	 $(selector).bootstrapValidator({
		    feedbackIcons: {
		        valid: 'fa fa-check',
		        invalid: 'fa fa-times',
		        validating: 'fa fa-refresh'
		    }
	  });
}

sy.setCookie = function(name,value,days,path){   
    var name = escape(name);   
    var value = escape(value);   
    var expires = new Date();   
    expires.setTime(expires.getTime() + days*24*3600000);   
    path = path == "" ? "" : ";path=" + path;   
    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();   
    document.cookie = name + "=" + value + _expires + path;   
}   

sy.delCookie = function(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = sy.getCookie(name);
	if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
} 

sy.getCookie = function(sName) {
    var aCookie = document.cookie.split("; ");
    var lastMatch = null;
    for (var i = 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0]) {
            lastMatch = aCrumb;
        }
    }
    if (lastMatch) {
        var v = lastMatch[1];
        if (v === undefined) return v;
        return unescape(v);
    }
    return null;
}

/**
 * 创建一个模式化的dialog
 * @requires jQuery,EasyUI
 * 
 */
sy.modalDialog = function(options) {
	if(options.width && options.height){
		options.area = [options.width+'px', options.height+'px'];
	}else if(options.width && !options.height){
		options.area = [options.width+'px'];
	}else if(!options.width && !options.height){
		options.area = ['640px'];
	}
	
	var opts = $.extend({
		type: options.url ? 2 : 1,
		title : '&nbsp;',
		shadeClose: true,
	    shade: 0.8,
	    maxmin:true
	}, options);
	
	if(options.buttons && options.buttons.length > 0){
		opts.btn = new Array();
		opts.btn[0] = options.buttons[0].text;
		opts.yes = options.buttons[0].handler;
		if(options.buttons[1]){
			opts.btn[1] = "取消";
			
			opts.btn[2] = options.buttons[1].text;
			opts.btn3 = options.buttons[1].handler;
		}
	}
	
	if (options.onClose){
		opts.end = options.onClose;
	}
	
	if (options.url) {
		opts.content = options.url;
	}else if(options.content){
		opts.content = options.content;
	}
	
	opts.index = layer.open(opts);

	var obj = $("#layui-layer"+opts.index);
	obj.extend({
		dialog: function(op){ 
			if(op == 'destroy'){
				layer.close(opts.index);
			}else if(op == 'index'){
				return opts.index;
			} 
		}
	});
	return obj;
	
	
/*	//easyui dialog
 	var opts = $.extend({
		title : '&nbsp;',
		width : 640,
		height : 480,
		modal : true,
		resizable:true,
		onClose : function() {
			$(this).dialog('destroy');
		}
	}, options);
	opts.modal = true;// 强制此dialog为模式化，无视传递过来的modal参数
	if (options.url) {
		opts.content = '<iframe id="" src="' + options.url + '" allowTransparency="true" scrolling="auto" width="100%" height="98%" frameBorder="0" name=""></iframe>';
	}
	return $('<div/>').dialog(opts);*/
};

/**
 * 更换主题
 * 
 * @requires jQuery,EasyUI
 * @param themeName

sy.changeTheme = function(themeName) {
	var $easyuiTheme = $('#easyuiTheme');
	var url = $easyuiTheme.attr('href');
	var href = url.substring(0, url.indexOf('themes')) + 'themes/' + themeName + '/easyui.css';
	$easyuiTheme.attr('href', href);

	var $iframe = $('iframe');
	if ($iframe.length > 0) {
		for (var i = 0; i < $iframe.length; i++) {
			var ifr = $iframe[i];
			try {
				$(ifr).contents().find('#easyuiTheme').attr('href', href);
			} catch (e) {
				try {
					ifr.contentWindow.document.getElementById('easyuiTheme').href = href;
				} catch (e) {
				}
			}
		}
	}

	sy.cookie('easyuiTheme', themeName, {
		expires : 7,path:"/"
	});
};
 */

/**
 * 获取datatable选择对象
 */
sy.fnGetSelected = function(oTable) {
    var aReturn = new Array();
    var aTrs = oTable.fnGetNodes();
    for (var i = 0; i < aTrs.length; i++) {
        if ($(aTrs[i]).hasClass('selected')) {
            aReturn.push(table.fnGetData(aTrs[i]));
        }
    }
    return aReturn;
}

/**
 * 滚动条
 * @requires jQuery,EasyUI
 */
sy.progressBar = function(options) {
	if (typeof options == 'string') {
		if (options == 'close') {
			$('#syProgressBarDiv').dialog('destroy');
		}
	} else {
		if ($('#syProgressBarDiv').length < 1) {
			var opts = $.extend({
				title : '&nbsp;',
				closable : false,
				width : 300,
				height : 60,
				modal : true,
				content : '<div id="syProgressBar" class="easyui-progressbar" data-options="value:0"></div>'
			}, options);
			$('<div id="syProgressBarDiv"/>').dialog(opts);
			$.parser.parse('#syProgressBarDiv');
		} else {
			$('#syProgressBarDiv').dialog('open');
		}
		if (options.value) {
			$('#syProgressBar').progressbar('setValue', options.value);
		}
	}
};
$.messager = $.messager||{};

$.messager.alert = function(){
	if(arguments.length == 1){
		layer.msg(arguments[0],{shift: 6,icon: 8,skin: 'layer-ext-seaning'});
	}else{
		layer.msg(arguments[1],{shift: 6,icon: 8,skin: 'layer-ext-seaning'});
	}
}

$.messager.i = function(){
	if(arguments.length == 1){
		layer.msg(arguments[0],{icon: 6,skin: 'layer-ext-seaning'});
		//$.messager.alert("信息",arguments[0],"info");
	}else{
		layer.msg(arguments[1],{icon: 6,skin: 'layer-ext-seaning'});
		//$.messager.alert(arguments[0],arguments[1],"info");
	}
}

$.messager.e = function(){
	if(arguments.length == 1){
		layer.msg(arguments[0],{icon: 11,skin: 'layer-ext-seaning'});
		//$.messager.alert("错误",arguments[0],"error");
	}else{
		layer.msg(arguments[1],{icon: 11,skin: 'layer-ext-seaning'});
		//$.messager.alert(arguments[0],arguments[1],"error");
	}
}

$.messager.q = function(){
	if(arguments.length == 1){
		layer.msg(arguments[0],{icon: 4,skin: 'layer-ext-seaning'});
		//$.messager.alert("问题",arguments[0],"question");
	}else{
		layer.msg(arguments[1],{icon: 4,skin: 'layer-ext-seaning'});
		//$.messager.alert(arguments[0],arguments[1],"question");
	}
}

$.messager.w = function(){
	if(arguments.length == 1){
		layer.msg(arguments[0], {shift: 6,icon: 8,skin: 'layer-ext-seaning'});
		//$.messager.alert("警告",arguments[0],"warning");
	}else{
		layer.msg(arguments[1], {shift: 6,icon: 8,skin: 'layer-ext-seaning'});
		//$.messager.alert(arguments[0],arguments[1],"warning");
	}
}

$.messager.confirm = function(title,content,func){
	layer.confirm(content, {
		icon: 4, 
		title:title
	}, function(index){
		layer.close(index);
		func(true);
	}, function(){
		
	});
}

$.messager.prompt = function(muti,content,func){
	layer.prompt({
	    formType: muti?2:0,
	    title: content
	}, function(value, index, elem){
		func(value);
		layer.close(index);
	});
}

$.messager.progress = function(config){
	if(config == undefined){
		layer.closeAll('dialog');
		layer.msg("数据加载中....", {icon: 16,time:0,shade: [0.3, '#000']});
	}else if(typeof config == 'object'){
		layer.closeAll('dialog');
		layer.msg(config.text, {icon: 16,time:0,shade: [0.3, '#000']});
	}else{
		layer.closeAll('dialog');
	}
}

/**id:待查看复制的id
 * title:对话框标题
 * */
sy.getId = function(id,title){
	parent.sy.modalDialog({
		title : title||'ID',
		width : 300,
		height : 200,
		maxmin:false,
		url :sy.contextPath +'/manager/admin/go/getid?id=' +id
	});
};

/**
 * 将form表单元素的值序列化成对象
 * 
 * @example sy.serializeObject($('#formId'))
 * @requires jQuery
 * 
 * @returns object
 */
sy.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (this['value'] != undefined && this['value'].length > 0) {// 如果表单项的值非空，才进行序列化操作
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + this['value'];
			} else {
				o[this['name']] = this['value'];
			}
		}
	});
	return o;
};


/**
 * 
 * @example sy.loadForm($('#formId'))
 * @requires jQuery
 * 
 * @returns object
 */
sy.loadForm = function(form,result) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (this['name'] != undefined && result[this['name']]!=undefined) {// 如果表单项的值非空，才进行序列化操作
			form.find('input[name='+this['name']+']').val(result[this['name']]);
			form.find('select[name='+this['name']+']').val(result[this['name']]);
			form.find('textarea[name='+this['name']+']').val(result[this['name']]);
		}
	});
	return o;
};


/**
 * 
 * @example sy.loadHtml($('#formId'))
 * @requires jQuery
 * 
 * @returns object
 */
sy.loadHtml = function(form,result) {
	var o = {};
	$.each(result, function(i,v) {
		if(form.find('[name='+i+']').length>0){
			form.find('[name='+i+']').html(v);
		}
	});
	return o;
};

Date.prototype.format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
